import { useMemo } from 'react';
import { Position } from 'reactflow';

import MyTooltip from '@/components/tooltip';
import { t } from '@/locales/i18n';
import { NodeInputKeyEnum } from '@/types/workflow/constant';
import { FlowNodeOutputItemType } from '@/types/workflow/io';
import { ClassifyQuestionAgentItemType } from '@/types/workflow/template/system/classifyQuestion/type';
import { getHandleId } from '@/types/workflow/utils';

import { SourceHandle } from '../render/Handle';
import { NodeCardProps } from '../render/NodeCard';

// 将组件定义移到外部
const AgentsRenderer = ({
  agents,
  nodeId,
}: {
  agents: ClassifyQuestionAgentItemType[];
  nodeId: string;
}) => (
  <div className="flex flex-col gap-2">
    {agents.map((item, i) => (
      <div key={item.key} className="relative flex w-full">
        <div className="mr-6 flex w-full min-w-0 items-center gap-1 overflow-hidden rounded-md bg-fill-2 px-2 py-[6px] text-xs font-font-weight-400 text-text-5">
          <div className="w-10 flex-shrink-0">{t('classification') + (i + 1)}</div>
          <MyTooltip title={item.value}>
            <div className="min-w-0 flex-1 overflow-hidden truncate">{item.value}</div>
          </MyTooltip>
        </div>
        <div className="absolute right-0 mt-3">
          <SourceHandle
            nodeId={nodeId}
            handleId={getHandleId(nodeId, 'source', item.key)}
            position={Position.Right}
            translate={[11, 0]}
          />
        </div>
      </div>
    ))}
  </div>
);

function NodeCQNodeFolded(props: NodeCardProps) {
  const { inputs, nodeId } = props;
  const inputString = useMemo(() => JSON.stringify(inputs), [inputs]);
  const copyInputs = useMemo(() => {
    return JSON.parse(inputString) as FlowNodeOutputItemType[];
  }, [inputString]);

  const agents = useMemo(() => {
    return copyInputs.find((input) => input.key === 'agents');
  }, [copyInputs]);

  return (
    <div className="mb-2 ml-2 p-2 text-text-4">
      <div className="flex w-full gap-2">
        <span className="flex-shrink-0">分类</span>
        <div className="min-w-0 flex-1">
          {agents && agents.key === NodeInputKeyEnum.agents && (
            <AgentsRenderer
              agents={agents.value as ClassifyQuestionAgentItemType[]}
              nodeId={nodeId}
            />
          )}
        </div>
      </div>
    </div>
  );
}

export default NodeCQNodeFolded;
